package com.edu.gcu.manager.service.impl;

import com.edu.gcu.manager.service.IReportService;
import com.edu.gcu.manager.vo.ReportVo;
import com.edu.gcu.system.common.Const;
import com.edu.gcu.system.common.ServerResponse;
import com.edu.gcu.system.dao.ReportMapper;
import com.edu.gcu.system.dao.UserMapper;
import com.edu.gcu.system.pojo.Report;
import com.edu.gcu.system.pojo.User;
import com.edu.gcu.system.util.DateTimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author polo
 * @version V1.0
 * @description: 举报service接口实现类
 * @date 2018-02-20-12:22
 */

@Service("iReportService")
public class IReportServiceImpl implements IReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse list(String title, String content, String orderBy, Integer pageNum, Integer pageSize) {
        // 分页
        PageHelper.startPage(pageNum, pageSize);
        // 排序规则
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.ReportOrderBy.CREATE_TIME_DESC_ASC.contains(orderBy)) {
                List<String> orderList = Splitter.on("-").splitToList(orderBy);
                PageHelper.orderBy(orderList.get(0) + " " + orderList.get(1));
            }
        }
        List<Report> reportList = reportMapper.selectList(StringUtils.isBlank(title) ? null : title,
                StringUtils.isBlank(content) ? null : content);
        System.out.println(reportList.size());
        List<ReportVo> reportVoList = this.assembleReportVo(reportList);
        PageInfo pageInfo = new PageInfo<>(reportList);
        pageInfo.setList(reportVoList);
        return ServerResponse.createBySuccess(pageInfo);

    }

    private List<ReportVo> assembleReportVo(List<Report> reportList) {
        List<ReportVo> reportVoList = Lists.newArrayList();
        for (Report report : reportList) {
            ReportVo reportVo = new ReportVo();
            BeanUtils.copyProperties(report, reportVo);
            reportVo.setCreateTime(DateTimeUtil.dateToStr(report.getCreateTime()));
            // 获取用户
            User user = userMapper.selectByPrimaryKey(report.getUserId());
            if (user != null) {
                BeanUtils.copyProperties(user, reportVo);
                reportVo.setSex(user.getSex() == 1 ? '男' : '女');
                reportVo.setAddress(user.getCountry() + user.getProvince() + user.getCity());
                reportVoList.add(reportVo);
            }
        }
        return reportVoList;
    }
}
